package motionblur.view;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.RenderingHints;
import java.awt.image.BufferStrategy;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JFrame;

import motionblur.Ball;
import motionblur.Settings;

public class MyFrame extends JFrame {
	
	private Canvas render = new Canvas();
	BufferStrategy bufferstrat = null;
	private List<Ball> balls;
	Timer timer = new Timer();
	
	public MyFrame(List<Ball> balls) {
		this.balls = balls;
		
        render = new Canvas();
        render.setIgnoreRepaint(true);
 
        add(render);
        pack();
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        render.createBufferStrategy(2);
        bufferstrat = render.getBufferStrategy();
        
        timer.scheduleAtFixedRate(new TimerTask() {
        	public void run() {
        		render();
        	};
        }, 0, 50);
	}
	
	public void goFullScreen(GraphicsDevice gd) {
		dispose();
		setResizable(false);
		setUndecorated(true);
		gd.setFullScreenWindow(this);
	}
	
	public void render(){
        do{
            do{
                Graphics2D g2d = (Graphics2D) bufferstrat.getDrawGraphics();
                
                this.paint(g2d);
                
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    					RenderingHints.VALUE_ANTIALIAS_ON);
    			g2d.setColor(Color.RED);
    			
    			renderBalls(g2d);
    			renderInfos(g2d);
 
                g2d.dispose();
             }while(bufferstrat.contentsRestored());
              bufferstrat.show();
        }while(bufferstrat.contentsLost());
    }

	private void renderBalls(Graphics2D g2d) {
		synchronized (balls) {
			for (Ball ball : balls) {
				g2d.fillOval(ball.getX(), ball.getY(), ball.getWidth(),
						ball.getHeight());
			}
		}
	}

	private void renderInfos(Graphics2D g2d) {
		if(Settings.getInstance().isShowInfos()) {
			g2d.setColor(Color.WHITE);
			g2d.setFont(new Font("Lucida Sans Unicode", Font.BOLD, 30));
			g2d.drawString("Bouncing balls", 50, 50);
		}		
	}
}
